package com.zt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zt.dto.CouponDistributionDto;
import com.zt.dto.UserQueryDto;
import com.zt.entity.Coupons;
import com.zt.entity.Result;
import com.zt.entity.Users;
import com.zt.service.CouponDistributionService;
import com.zt.service.CouponDistributionRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 优惠券发放控制器
 */
@RestController
@RequestMapping("/admin/coupon-distribution")
@Slf4j
public class CouponDistributionController {
    
    @Autowired
    private CouponDistributionService couponDistributionService;

    @Autowired
    private CouponDistributionRedisService couponDistributionRedisService;
    
    /**
     * 获取已激活的优惠券列表
     */
    @GetMapping("/active-coupons")
    public Result getActiveCoupons() {
        try {
            List<Coupons> coupons = couponDistributionService.getActiveCoupons();
            
            // 为每个优惠券添加已发放数量信息
            for (Coupons coupon : coupons) {
                Integer distributedCount = couponDistributionService.getCouponDistributedCount(coupon.getId());
                // 可以通过扩展字段或Map返回
                Map<String, Object> couponInfo = new HashMap<>();
                couponInfo.put("coupon", coupon);
                couponInfo.put("distributedCount", distributedCount);
            }
            
            return Result.success("获取成功", coupons);
        } catch (Exception e) {
            log.error("获取激活优惠券列表失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }
    
    /**
     * 分页查询用户列表
     */
    @PostMapping("/users")
    public Result getUserList(@RequestBody UserQueryDto userQueryDto) {
        try {
            IPage<Users> userPage = couponDistributionService.getUserList(userQueryDto);
            return Result.success("查询成功", userPage);
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 发放优惠券
     */
    @PostMapping("/distribute")
    public Result distributeCoupons(@RequestBody CouponDistributionDto distributionDto) {
        try {
            return couponDistributionService.distributeCoupons(distributionDto);
        } catch (Exception e) {
            log.error("发放优惠券失败", e);
            return Result.error("发放失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查用户是否已拥有优惠券
     */
    @GetMapping("/check-user-coupon")
    public Result checkUserCoupon(@RequestParam Integer userId, @RequestParam Integer couponId) {
        try {
            boolean hasCoupon = couponDistributionService.hasUserCoupon(userId, couponId);
            return Result.success("检查成功", hasCoupon);
        } catch (Exception e) {
            log.error("检查用户优惠券失败", e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取优惠券发放统计
     */
    @GetMapping("/coupon-stats/{couponId}")
    public Result getCouponStats(@PathVariable Integer couponId) {
        try {
            // 使用新的统计方法，包含更详细的信息
            var stats = couponDistributionService.getCouponDistributionStats(couponId);
            if (stats == null) {
                return Result.error("优惠券不存在");
            }
            return Result.success("获取成功", stats);
        } catch (Exception e) {
            log.error("获取优惠券统计失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 为新用户发放默认优惠券
     */
    @PostMapping("/give-new-user-coupon")
    public Result giveNewUserCoupon(@RequestParam Long userId, @RequestParam Integer defaultCouponId) {
        try {
            return couponDistributionService.giveNewUserCoupon(userId, defaultCouponId);
        } catch (Exception e) {
            log.error("为新用户发放优惠券失败", e);
            return Result.error("发放失败：" + e.getMessage());
        }
    }

    /**
     * 为新用户发放默认优惠券（Redis格式）
     * 使用 couponRedisTemplate.opsForValue().set(couponsKey, couponsJson, NEW_USER_COUPON_TTL, TimeUnit.DAYS);
     */
    @PostMapping("/give-new-user-coupon-redis")
    public Result giveNewUserCouponRedis(@RequestParam Long userId) {
        try {
            couponDistributionRedisService.giveNewUserCoupon(userId);
            return Result.success("新用户优惠券发放成功（Redis格式）");
        } catch (Exception e) {
            log.error("为新用户发放优惠券失败（Redis格式）", e);
            return Result.error("发放失败：" + e.getMessage());
        }
    }

    /**
     * 为用户发放指定优惠券（Redis格式）
     */
    @PostMapping("/distribute-coupon-redis")
    public Result distributeCouponRedis(@RequestParam Long userId, @RequestParam Integer couponId) {
        try {
            couponDistributionRedisService.distributeCouponToUser(userId, couponId);
            return Result.success("优惠券发放成功（Redis格式）");
        } catch (Exception e) {
            log.error("为用户发放优惠券失败（Redis格式）", e);
            return Result.error("发放失败：" + e.getMessage());
        }
    }

    /**
     * 通用优惠券发放接口（Redis格式）
     * 使用 couponRedisTemplate.opsForValue().set(couponsKey, couponsJson, NEW_USER_COUPON_TTL, TimeUnit.DAYS)
     */
    @PostMapping("/distribute-coupon-with-cache")
    public Result distributeCouponWithCache(@RequestParam Long userId,
                                          @RequestParam Integer couponId,
                                          @RequestParam(defaultValue = "管理员发放") String source) {
        try {
            couponDistributionRedisService.distributeCouponWithRedisCache(userId, couponId, source);
            return Result.success("优惠券发放成功，已更新Redis缓存");
        } catch (Exception e) {
            log.error("通用优惠券发放失败", e);
            return Result.error("发放失败：" + e.getMessage());
        }
    }

    /**
     * 活动优惠券发放接口（Redis格式）
     * 专门用于活动场景的优惠券发放
     */
    @PostMapping("/distribute-activity-coupon")
    public Result distributeActivityCoupon(@RequestParam Long userId,
                                         @RequestParam Integer couponId,
                                         @RequestParam String activityName) {
        try {
            couponDistributionRedisService.distributeActivityCoupon(userId, couponId, activityName);
            return Result.success("活动优惠券发放成功，已更新Redis缓存");
        } catch (Exception e) {
            log.error("活动优惠券发放失败", e);
            return Result.error("发放失败：" + e.getMessage());
        }
    }

    /**
     * 批量发放优惠券（Redis格式）
     */
    @PostMapping("/batch-distribute-redis")
    public Result batchDistributeCouponsRedis(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> userIds = (List<Integer>) request.get("userIds");
            Integer couponId = (Integer) request.get("couponId");

            couponDistributionRedisService.batchDistributeCoupons(userIds, couponId);
            return Result.success("批量优惠券发放成功（Redis格式）");
        } catch (Exception e) {
            log.error("批量发放优惠券失败（Redis格式）", e);
            return Result.error("发放失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户优惠券缓存（Redis格式）
     */
    @GetMapping("/user-coupons-cache/{userId}")
    public Result getUserCouponsCache(@PathVariable Long userId) {
        try {
            List<Map<String, Object>> coupons = couponDistributionRedisService.getUserCouponsFromCache(userId);
            Map<String, Object> result = new HashMap<>();
            result.put("userId", userId);
            result.put("coupons", coupons);
            result.put("count", coupons.size());
            return Result.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取用户优惠券缓存失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 删除用户优惠券缓存
     */
    @DeleteMapping("/user-coupons-cache/{userId}")
    public Result deleteUserCouponsCache(@PathVariable Long userId) {
        try {
            couponDistributionRedisService.deleteUserCouponsCache(userId);
            return Result.success("用户优惠券缓存删除成功");
        } catch (Exception e) {
            log.error("删除用户优惠券缓存失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 查询所有发放的优惠券
     * @param userId 用户ID（可选）
     * @param status 优惠券状态（可选）1-未使用，2-已使用
     * @param couponId 优惠券ID（可选）
     */
    @GetMapping("/distributed-coupons")
    public Result queryDistributedCoupons(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer couponId) {
        try {
            List<Map<String, Object>> distributedCoupons =
                couponDistributionRedisService.queryDistributedCoupons(userId, status, couponId);

            Map<String, Object> result = new HashMap<>();
            result.put("coupons", distributedCoupons);
            result.put("total", distributedCoupons.size());

            Map<String, Object> queryConditions = new HashMap<>();
            queryConditions.put("userId", userId);
            queryConditions.put("status", status);
            queryConditions.put("couponId", couponId);
            result.put("queryConditions", queryConditions);

            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("查询发放优惠券失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
}
